'''
惠多保重大疾病保险
'''
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests
from common.helper import Helper
from threading import Thread
from pprint import pprint


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "惠多保重大疾病保险"

    # 生产产品数据
    def genProductInfo(self):

        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 5)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", '150000', '200000', '250000', '300000'],
                # 保障期间
                "expire": ["70岁", "80岁", "终身"],
                # 缴费期间 0 趸交
                "interval": ["0", "5", "10", "15", "20"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(5, 50)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", '150000', '200000', '250000', '300000', '350000', '400000', '450000', '500000'],
                # 保障期间
                "expire": ["70岁", "80岁", "终身"],
                # 缴费期间 0 趸交
                "interval": ["0", "5", "10", "15", "20"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(5, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", '150000', '200000', '250000', '300000', '350000', '400000', '450000', '500000'],
                # 保障期间
                "expire": ["70岁", "80岁", "终身"],
                # 缴费期间 0 趸交
                "interval": ["0", "5", "10", "15", "20"]
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000", '150000', '200000'],
                # 保障期间
                "expire": ["70岁", "80岁", "终身"],
                # 缴费期间 0 趸交
                "interval": ["0", "5", "10"]
            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(56, 61)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["100000"],
                # 保障期间
                "expire": ["70岁", "80岁", "终身"],
                # 缴费期间 0 趸交
                "interval": ["0", "5"]
            }

        }

        for k in plan:

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["expire"],
                             plan[k]["interval"]):
                # 写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3], v[4]
                ))
                self.mysql._conn.commit()

                print(

                    domain[self.name]["insert_sql"].format(

                        v[0], v[1], v[2], v[3], v[4]
                    )
                )

    # 执行爬虫
    def requestJson(self,dt=None,mysql=None):

        if dt["gender"] == "M":

            sex = "0"

        else:

            sex = "1"


        data = {

            "insuredsStr":'[{"birthday":"'+str(2019 - int(dt["year"]))+'-12-18","sex":"'+sex+'","planInfos":[{"riskCode":"I158","mainRiskCode":"I158","planCode":"32","planPeriod":"'+dt["expire"]+'","payType":"0","payEndYearFlag":"","payEndYear":'+dt["interval"]+',"dutys":[{"dutyCode":"513001","dutyAmnt":"'+dt["money"]+'"}]}]}]',
            "isOrder": "0",
            "productID": "36"

        }

        payload = urlencode(data)

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        if '保费计算_[0]被保人_未查询到对应费率，无法计算保费！' in r.text:

            # 任务执行失败
            data = {
                "name":self.name,
                "state":3,
                "id":dt["id"]
            }

            mysql.updateTask( data )
            print("/*产品价格更新失败:%d*/"%dt["id"])

        else:

            price = Helper.decimalParse(r.json()["data"]["data"]["premiun"])

            data = {
                "name":self.name,
                "price":price,
                "id":dt["id"]
            }
            mysql.updatePrice( data )

    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt=dt, mysql=mysql)

    def startProcess(self):

        threads = []

        for i in range(5):

            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()

            threads.append(t)

        for t in threads:

            t.join()
